<?php


namespace app\api\controller;

use app\common\model\Comment as C;
use think\exception\ValidateException;
use app\common\validate\Comment as CommentValidate;
use think\facade\Db;

class Comment extends Base
{

    public function commentAdd()
    {
        $postId = input("postId");
        $sessionKey = input("sessionKey");
        $content = input("content");

        $data["uid"] = $this->getUid($sessionKey);
        $data["pid"] = $postId;
        $data["content"] = $content;

        try {
            validate(CommentValidate::class)->check($data);
        } catch (ValidateException $e) {
            // 验证失败 输出错误信息
            return json(["code" => 0,"msg" =>$e->getError()]);
        }

        $create = C::create($data);
        if ($create){
            return json(["code" => 1,"msg" => "评论成功"]);
        }
        return json(["code" => 0,"msg" => "评论失败"]);
    }

    public function postComment()
    {
        $postId = input("id");
        $res = C::where("pid",$postId)->order("id desc")->field("uid,content,create_time")->select()->toArray();

        foreach ($res as $key =>$item){
            $userInfo = Db::name("user")->field("username,avatar")->where("uid",$item["uid"])->find();
            $res[$key]["userInfo"] = $userInfo;
        }
        return json($res);
    }
}